﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MatchmakingController.cs" company="DissingNellemann">
//   
// All rights reserved </copyright>
// <summary>
//   The matchmaking controller.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Website.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using Website.CRUDServices;
    using Website.Models;
    using Website.Models.Styling;
    using Website.Models.ViewModels;

    /// <summary>
    ///     The matchmaking controller.
    /// </summary>
    [Authorize(Roles = "User, Admin")]
    public class MatchmakingController : BaseController
    {
        #region Public Methods and Operators

        /// <summary>
        ///     The get header items.
        /// </summary>
        /// <returns>
        ///     The list of headeritems for a matchmaking view.
        /// </returns>
        public static List<TableViewHeaderItem> GetHeaderItems()
        {
            var headerItems = new List<TableViewHeaderItem>();
            var item1 = new TableViewHeaderItem { Text = "Dato", SortableName = "Date", IsSortable = true, };
            var item2 = new TableViewHeaderItem { Text = "Overskrift", SortableName = "Name", IsSortable = true };
            var item3 = new TableViewHeaderItem { Text = "Profiler", SortableName = string.Empty, IsSortable = false };
            var item4 = new TableViewHeaderItem { Text = "Projekt", SortableName = string.Empty, IsSortable = false };
            headerItems.Add(item1);
            headerItems.Add(item2);
            headerItems.Add(item3);
            headerItems.Add(item4);

            return headerItems;
        }

        /// <summary>
        /// The index.
        /// </summary>
        /// <param name="skip">
        /// The skip.
        /// </param>
        /// <param name="take">
        /// The take.
        /// </param>
        /// <param name="orderBy">
        /// The order by.
        /// </param>
        /// <param name="sortAscending">
        /// The sort ascending.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult Index(int? skip, int? take, string orderBy, bool? sortAscending)
        {
            this.Session["CurrentSubMenuSelection"] = "Matchmaking";

            ListView<Matchmaking> view = null;

            List<TableViewHeaderItem> headerItems = GetHeaderItems();

            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var query = new MatchmakingQuery
                    {
                        Settings =
                            new SearchSettings
                            {
                                SortAscending =
                                    sortAscending ?? false,
                                Skip = skip ?? 0,
                                Take = take ?? 20,
                                OrderBy =
                                    !string.IsNullOrEmpty(
                                        orderBy)
                                        ? orderBy
                                        : "Date"
                            }
                    };

                    IResult iRes = client.Query(query);
                    if (iRes != null)
                    {
                        var res = (MatchmakingResult)iRes;
                        view = new ListView<Matchmaking>(
                            res.List.ToList(),
                            skip ?? 0,
                            take ?? 20,
                            res.TotalRowCount,
                            query.Settings.OrderBy,
                            sortAscending ?? false,
                            headerItems,
                            "Index");


                        this.ViewData["Profiles"] = PrimitiveTypes.GetProfiles();
                        this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
                    }
                });

            return View(view);
        }

        /// <summary>
        ///     The new matchmaking.
        /// </summary>
        /// <returns>
        ///     The <see cref="ActionResult" />.
        /// </returns>
        public ActionResult NewMatchmaking()
        {
            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Funds"] = PrimitiveTypes.GetFunds();
            this.ViewData["PartnerTypes"] = PrimitiveTypes.GetMatchmakingPartnerTypes();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
            this.ViewData["Locations"] = PrimitiveTypes.GetLocations();
            this.ViewData["Profiles"] = PrimitiveTypes.GetProfiles();

            //// grab profiles
            //ProfilesView pv = ProfilesView.GetRelated();
            //pv.SortAscending = true;
            //pv.Skip = 0;
            //pv.Take = 10000;
            //pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
            //this.ViewData["Profiles"] = pv;
            return View();
        }

        /// <summary>
        /// The new matchmaking.
        /// </summary>
        /// <param name="mm">
        /// The mm.
        /// </param>
        /// <param name="mp">
        /// The mp.
        /// </param>
        /// <param name="ownerProjects">
        /// The owner projects.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        [HttpPost]
        [ValidateInput(false)] 
        public ActionResult NewMatchmaking(Matchmake mm, MatchmakingPartner mp, List<Guid> ownerProjects)
        {
            // finish the MatchmakingPartner object
            mp.ID = Guid.NewGuid();
            var guidTransfer = new[] { mp.ID };

            // fill up dto
            var theMatch = new Matchmaking
            {
                ID = Guid.NewGuid(),
                Name = mm.Name,
                Location = mm.Location,
                Date = mm.Date,
                Buyers = mm.Buyers,
                Funds = (mm.Funds ?? new List<Guid>()).ToArray(),
                FundsText = mm.FundsText,
                Partners = (mp.Type != null && mp.Type != Guid.Empty ? guidTransfer : new List<Guid>().ToArray() ),
                Profiles = (mm.Profiles ?? new List<Guid>()).ToArray(),
                OtherFinancing = (mm.OtherFinancing ?? new List<Guid>()).ToArray(),
                Comments = mm.Comments,
                OwnerProjects = (ownerProjects ?? new List<Guid>()).ToArray(),
            };

             
            // save the matchmake
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    if (mp.Type != null && mp.Type != Guid.Empty)
                    {
                        var cmd = new CreateMatchmakingPartnerCommand { NewMatchmakingPartner = mp };
                        client.ExecuteCommand(cmd);

                    }

                    var cmd2 = new CreateMatchmakingCommand { NewMatchmaking = theMatch };
                    client.ExecuteCommand(cmd2);
                });
            return this.RedirectToAction("Index");
        }

        public ActionResult UpdateMatchmaking(Guid id)
        {

            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Funds"] = PrimitiveTypes.GetFunds();
            this.ViewData["PartnerTypes"] = PrimitiveTypes.GetMatchmakingPartnerTypes();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
            this.ViewData["Locations"] = PrimitiveTypes.GetLocations();
            this.ViewData["Profiles"] = PrimitiveTypes.GetProfiles();

            // load object for editing
            var mm = new Matchmaking();
            var mmp = new MatchmakingPartner();
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    //get the Matchmaking object
                    var query = new MatchmakingQuery { Settings = new SearchSettings { IDEquals = id } };
                    var res = client.Query(query) as MatchmakingResult;
                    if (res != null)
                    {
                        if (res.List.Any())
                        {
                            mm = res.List[0];
                        }
                    }
                    //get the MatchMakingPartner object
                    if (mm.Partners != null && mm.Partners.Any())
                    {
                        var query2 = new MatchmakingPartnerQuery { Settings = new SearchSettings { IDEquals = mm.Partners[0] } };
                        var res2 = client.Query(query2) as MatchmakingPartnerResult;
                        if (res2 != null)
                        {
                            if (res2.List.Any())
                            {
                                mmp = res2.List[0];
                            }
                        }
                        this.ViewData["Partners"] = mmp;
                    }
                });

            // ensure we have some content
            if (mm != null)
            {
                return View(mm);
            }

            // something buggered up. Better send them back to the index.
            return this.RedirectToAction("Index");
        }

        [HttpPost]
        [ValidateInput(false)] 
        public ActionResult UpdateMatchmaking(Guid id, Guid? partnerId, Matchmake mm, MatchmakingPartner mp, List<Guid> ownerProjects)
        {
            // finish the MatchmakingPartner object
            bool hasPartner;
            if (partnerId.HasValue && partnerId != Guid.Empty) { mp.ID = partnerId.Value; hasPartner = true; } else { mp.ID = Guid.NewGuid(); hasPartner = false; }
            var guidTransfer = new[] { mp.ID };

            // fill up dto
            var theMatch = new Matchmaking
            {
                ID = id,
                Name = mm.Name,
                Location = mm.Location,
                Date = mm.Date,
                Buyers = mm.Buyers,
                Funds = (mm.Funds ?? new List<Guid>()).ToArray(),
                Profiles = (mm.Profiles ?? new List<Guid>()).ToArray(),
                FundsText = mm.FundsText,
                Partners = (mp.Type != null && mp.Type != Guid.Empty ? guidTransfer : new List<Guid>().ToArray()),
                OtherFinancing = (mm.OtherFinancing ?? new List<Guid>()).ToArray(),
                Comments = mm.Comments,
                OwnerProjects = (ownerProjects ?? new List<Guid>()).ToArray(),
            };

            // save the matchmake
            CRUDServiceProvider.WithCRUDService(
                client =>
                {

                    if (mp.Type != null && mp.Type != Guid.Empty)
                    {
                        if (hasPartner)
                        {
                            var cmd = new UpdateMatchmakingPartnerCommand { Dto = mp };
                            client.ExecuteCommand(cmd);
                        }
                        else
                        {
                            var cmd = new CreateMatchmakingPartnerCommand { NewMatchmakingPartner = mp };
                            client.ExecuteCommand(cmd);
                        }
                    }
                    var cmd2 = new UpdateMatchmakingCommand { Dto = theMatch };
                    client.ExecuteCommand(cmd2);
                });
            return this.RedirectToAction("Index");
        }


        public ActionResult ViewMatchmaking(Guid id)
        {
            this.Init("Events");
            this.Session["SubMenuItems"] = ActivityController.CreateSubMenu();
            this.Session["CurrentSubMenuSelection"] = "Matchmaking";

            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Funds"] = PrimitiveTypes.GetFunds();
            this.ViewData["PartnerTypes"] = PrimitiveTypes.GetMatchmakingPartnerTypes();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
            this.ViewData["Locations"] = PrimitiveTypes.GetLocations();
            this.ViewData["Profiles"] = PrimitiveTypes.GetProfiles();

            // load object for editing
            var mm = new Matchmaking();
            var mmp = new MatchmakingPartner();
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    //get the Matchmaking object
                    var query = new MatchmakingQuery { Settings = new SearchSettings { IDEquals = id } };
                    var res = client.Query(query) as MatchmakingResult;
                    if (res != null)
                    {
                        if (res.List.Any())
                        {
                            mm = res.List[0];
                        }
                    }
                    //get the MatchMakingPartner object
                    if (mm.Partners != null && mm.Partners.Any())
                    {
                        var query2 = new MatchmakingPartnerQuery { Settings = new SearchSettings { IDEquals = mm.Partners[0] } };
                        var res2 = client.Query(query2) as MatchmakingPartnerResult;
                        if (res2 != null)
                        {
                            if (res2.List.Any())
                            {
                                mmp = res2.List[0];
                            }
                        }
                        this.ViewData["Partners"] = mmp;
                    }
                });

            // ensure we have some content
            if (mm != null)
            {
                return View(mm);
            }

            // something buggered up. Better send them back to the index.
            return this.RedirectToAction("Index");
        }


        public ActionResult DeleteMatchmaking(Guid id)
        {
            CRUDServiceProvider.WithCRUDService(client =>
            {
                CRUDServices.DeleteMatchmakingCommand cmd = new DeleteMatchmakingCommand() { Dto = id };
                client.ExecuteCommand(cmd);
            });

            return RedirectToAction("Index");
        }


        #endregion
    }
}